﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Pg.BioMedics.SDR.Caching.Configuration;

namespace Pg.BioMedics.SDR.Caching
{
    /// <summary>
    /// Represents a main entry point for caching framework. 
    /// All particular cache contexts should derevie from this class
    /// </summary>
    public abstract class BaseCacheContext
    {
        #region Fields

        private string cacheName;
        private bool inProcess;

        #endregion

        #region Constructors

        /// <summary>
        /// Provides base cache context initialization logic
        /// </summary>
        internal protected BaseCacheContext()
        {
            try
            {
                LoadConfiguration();
            }
            catch (Exception ex)
            {
                throw new CachingException("Couldnot execute base cache context initialization", ex);
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Creates caching strategy for the given type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keySelector">Entity key selector</param>
        /// <returns></returns>
        protected ICachingStrategy<T> CreateCachingStrategy<T>()
        {
            try
            {
                if (this.inProcess)
                    return new LocalCachingStrategy<T>();
                else
                    return new DistributedCachingStrategy<T>(this.cacheName);
            }
            catch (Exception ex)
            {
                throw new CachingException("Couldnot create caching strategy", ex);
            }
        }

        #endregion

        #region Support methods

        /// <summary>
        /// Loads configuration from the corresponding configuration section
        /// </summary>
        private void LoadConfiguration()
        {
            CachingConfigurationSection configuration = CachingConfigurationSection.GetConfiguration();
            if (configuration.Settings != null)
                this.cacheName = configuration.Settings.CacheName;

            if (configuration.Settings != null)
                this.inProcess = configuration.Settings.InProcess;
            else
                this.inProcess = true;
        }

        #endregion
    }
}
